//
//  PhotoAndVideoSelectTool.swift
//  YDPhotoPicker
//
//  Created by alyadan on 16/8/17.
//  Copyright © 2016年 alyadan. All rights reserved.
//

import UIKit
import MobileCoreServices
import YD_Util
import Photos
import MVVM_BaseViewController
import RxSwift
import RxCocoa
import YD_ProgressHUD

//public protocol cropImageProtocol {
//    func cropImage(image:UIImage)
//}

public class PhotoAndVideoSelectTool: NSObject, UIImagePickerControllerDelegate ,UINavigationControllerDelegate ,PECropViewControllerDelegate, cropImageProtocol{
    
    public typealias PhotoToolCompleteBlock = (AnyObject?) -> Void
    public typealias PhotoToolCancelBlock = () -> Void
    public var selectType:PhotoAndVideoSelctType = .AlbumPhoto
    public var maxCount = 9
    public var neetCut = false
    public var orignalData = false
    public var cropSquare = false
    public var cropCustomRatio: CGFloat = 0.0
    public var completeCallBack : PhotoToolCompleteBlock?
    public var cancelCallBack : PhotoToolCancelBlock?
    public var shouldShowAlbumList = true
    
    lazy var albumSelector:YDPhotoVCModel = YDPhotoVCModel(parentViewModel: nil,selectType: 0, maxSelectNum: self.maxCount,orignalData: self.orignalData, cropImageDelegate: self)
    
    
    lazy var imagePicker:UIImagePickerController =  {
        let x = UIImagePickerController()
        
        x.modalPresentationStyle = .overFullScreen
        x.sourceType = .camera
        x.delegate = self
        return x
    }()
    
    
    public func setup(type:PhotoAndVideoSelctType = .AlbumPhoto, maxCount:Int = 9, neetCut:Bool = false, orignalData:Bool = false, cropSquare: Bool = false,complete:PhotoToolCompleteBlock?, cancelBlock:PhotoToolCancelBlock? = nil){
        self.selectType = type
        self.maxCount = maxCount
        self.neetCut = neetCut
        completeCallBack = complete
        self.orignalData = orignalData
        self.cancelCallBack = cancelBlock
        self.cropSquare = cropSquare
        if self.cropSquare {
            self.cropCustomRatio = 1.0
        }
    }
    
    
    func presentPicker(viewController: UIViewController) {
        if selectType == .AlbumPhoto || selectType == .AlbumVideo{
            if selectType == .AlbumPhoto {
                albumSelector.selectType = 0
                albumSelector.imagesCallback  = {[weak self] (imgs:[UIImage]) in
                    if imgs.count == 1 {
                        self?.cropImage(image: imgs[0])
                        return
                    }
                    self!.completeCallBack?(imgs as AnyObject?)
                }
            }else{
                albumSelector.selectType =  1
                albumSelector.videoCallBack = {[weak self] ( _ ,localURL:NSURL?) in
                    self!.completeCallBack?(localURL)
                }
            }
            
            let nav = PhotoNavgationController()
            albumSelector.orignalData = orignalData
            albumSelector.maxSelectNum = maxCount
            if let vcArr = albumSelector.getViewControllersArr() {
                if shouldShowAlbumList {
                    nav.viewControllers = vcArr
                }else{
                    nav.viewControllers = vcArr.count == 1 ? vcArr : [vcArr[1]]
                }
                
                viewController.present(nav, animated: true, completion: nil)
            }else{
                printLog("getViewControllersArr failed!")
            }
        }else if selectType == .CameraPhoto {
            imagePicker.mediaTypes = [String(kUTTypeImage)]
            imagePicker.cameraCaptureMode = .photo
            viewController.present(imagePicker, animated: true, completion: nil)
        }else if selectType == .CameraVideo {
            imagePicker.mediaTypes = [String( kUTTypeMovie)]
            imagePicker.cameraCaptureMode = .video
            viewController.present(imagePicker, animated: true, completion: nil)
        }
    }
    
    public func startPick(viewController:UIViewController){
        
        PHPhotoLibrary.requestAuthorization { (x:PHAuthorizationStatus) in
            switch x{
            case .authorized:
                print(Thread.isMainThread)
                DispatchQueue.main.async {
                    self.presentPicker(viewController: viewController)
                }
                return
            case .denied:
                YD_HUDCenter.share.svpHud.showMessage(message:"请到设置里打开相册权限!" )
                break
            case .notDetermined:
                self.startPick(viewController: viewController)
            default:
                return
            }
        }
        
    }
    
    //MARK:UIImagePickerControllerDelegate
    
    
    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        //    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if selectType == .CameraPhoto {
            if var image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage{
                
                
                if neetCut {
                    imagePicker.dismiss(animated: false, completion: { [weak self] in
                        self?.cropImage(image: image)
                    })
                    return
                }
                
                //                if let x = image.fixOrientation() {
                //                    image = x
                //                }
                
                completeCallBack?([image] as AnyObject)
            }
        }else if selectType == .CameraVideo{
            completeCallBack?(info[UIImagePickerController.InfoKey.mediaURL] as AnyObject?)
            //            UIImage().imageOrientation
        }
        
        imagePicker.dismiss(animated: true, completion: nil)
    }
    
    public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        completeCallBack?(nil)
        imagePicker.dismiss(animated: true, completion: nil)
    }
    
    //MARK: cropImage relative
    public func cropImage(image:UIImage){
        
        if self.neetCut == false {
            self.completeCallBack?([image] as AnyObject?)
            return
        }
        
        let cropVC = PECropViewController()
        cropVC.image = image
        cropVC.delegate = self
        print(self.cropSquare)
        cropVC.customCropRatio = self.cropCustomRatio
        
        CommonMethod.getCurrentVC()?.present(UINavigationController.init(rootViewController: cropVC), animated: false, completion: nil)
    }
    
    //MARK:PECropViewControllerDelegate
    public   func cropViewControllerDidCancel(_ controller: PECropViewController!) {
        cancelCallBack?()
        controller.dismiss(animated: true, completion: nil)
    }
    
    public   func cropViewController(_ controller: PECropViewController!, didFinishCroppingImage croppedImage: UIImage!) {
        completeCallBack?([croppedImage] as AnyObject)
        controller.dismiss(animated: true, completion: nil)
    }
    
    deinit {
        print("----------")
    }
}

@objc public enum PhotoAndVideoSelctType:Int {
    case AlbumPhoto
    case AlbumVideo
    case CameraPhoto
    case CameraVideo
}

